import React, { Component, PropTypes } from 'react';
import { connect } from "react-redux";
import { messages } from "share/common";
import { Button, Input, Modal } from 'antd'
import languageGrey from 'images/components/language-grey.svg';
import languageBlue from 'images/components/language.svg';
import 'styles/components/template/input-language.scss'

const TextArea = Input.TextArea;

class InputLanguage extends Component {

  backendList = {
    'zh_CN': 'zh_cn',
    'en': 'en',
    'ja': 'ja',
    'zh_TW': 'zh_TW',
    'it_IT': 'it_IT'
  };

  backendListFit = {
    'zh_CN': 'zh_CN',
    'en': 'en',
    'ja': 'ja',
    'zh_TW': 'zh_TW',
    'it_IT': 'it_IT'
  }

  state = {
    name: '',
    i18n: [],
    modalVisible: false
  };

  componentDidMount() {
    this.setValues(this.props.value);
  }

  componentWillReceiveProps(nextProps) {
    this.setValues(nextProps.value);
  }

  setValues = value => {
    const { languageList, language } = this.props;
    let { i18n } = this.state;
    if(value && value.i18n && Array.isArray(value.i18n) && value.i18n.length > 0) {
      let i18nFromValue = value.i18n;
      i18n = languageList.map(lan => {
        let targetI18n = i18nFromValue.find(i => (i.language === this.backendList[lan.code] || i.language === this.backendListFit[lan.code]));
        return {
          language: this.backendList[lan.code],
          value: targetI18n ? targetI18n.value : '',
        }
      });
      let mainI18n = i18nFromValue.find(i => i.language.toLowerCase() === language.code.toLowerCase());
      this.setState({ i18n, name: mainI18n ? mainI18n.value : '' });
    } else {
      this.setState({
        i18n: languageList.map(lan => ({
          language: this.backendList[lan.code],
          value: ''
        })),
        name: (value && value.name) ? value.name : ''
      })
    }
  };

  onChangeMainInput = e => {
    const { i18n, name } = this.state;
    const { language } = this.props;
    let value = e.target.value;
    i18n.forEach(i => {
      if(i.language.toLowerCase() === language.code.toLowerCase() || name === i.value)
        i.value = value;
      return i;
    });
    this.setState({
      name: value,
      i18n
    }, this.dispatchOnChange)
  };

  getLanguageInputValue = code => {
    const { i18n } = this.state;
    let targetI18n = i18n.find(i => i.language === this.backendList[code]);
    return targetI18n ? targetI18n.value : '';
  };

  onChangeLanguageInput = (e, code) => {
    const { i18n } = this.state;
    let { name } = this.state;
    const { language } = this.props;
    i18n.forEach(i => {
      if(i.language === this.backendList[code])
        i.value = e.target.value;
      return i;
    });
    if(this.backendList[code].toLowerCase() === language.code.toLowerCase())
      name = e.target.value;
    this.setState({ i18n, name }, this.dispatchOnChange);
  };

  onChange = () => {
    const { onChange } = this.props;
    const { name, i18n } = this.state;
    onChange && onChange({
      name,
      i18n
    });
  };

  dispatchOnChange = () => {
    this.onChange();
  };

  getMaxLength = code => {
    const { maxLength } = this.props;
    if(typeof maxLength === 'number') {
      return maxLength;
    }
    if(Array.isArray(maxLength)) {
      let targetLanguage = maxLength.find(i => i.language.toLowerCase() === code.toLowerCase());
      return targetLanguage ? targetLanguage.length : 500;
    }
    return 500;
  };

  renderIcon = () => (
    <span
      className='input-language-icon'
      onClick={this.toState({ modalVisible: true }, ()=>{this.props.clickedI18n && this.props.clickedI18n()})}
    >
      <img src={languageGrey} className='input-language-icon-grey'/>
      <img src={languageBlue} className='input-language-icon-blue'/>
    </span>
  );


  render() {
    const { modalVisible, name } = this.state;
    const { languageList, language, placeholder = '', disabled, textArea, extraProps } = this.props;
    let mainInputProps = {
      placeholder,
      value: name,
      onChange: this.onChangeMainInput,
      maxLength: this.getMaxLength(language.code), //这里maxLength必被React转成string，警告去不掉，我佛了
      disabled,
      ...extraProps
    };
    let Comp = textArea ? TextArea : Input;
    return (
      <div className='input-language'>
        {this.renderIcon()}
        {React.createElement(Comp, mainInputProps)}
        <Modal
          visible={modalVisible}
          zIndex={2000}
          title={messages('common-1.key395')/*语言设置*/}
          onCancel={this.toState({ modalVisible: false }, ()=>{this.props.clickedHideI18n && this.props.clickedHideI18n()})}
          className='input-language-modal'
          footer={[
            <Button key='ok' onClick={this.toState({ modalVisible: false }, ()=>{this.props.clickedHideI18n && this.props.clickedHideI18n()})}>
              {messages('common.ok')/*确定*/}
            </Button>
          ]}
        >
          {languageList.map(lan => {
            let languageInputProps = {
              disabled,
              placeholder,
              value: this.getLanguageInputValue(lan.code),
              onChange: e => this.onChangeLanguageInput(e, lan.code),
              maxLength: this.getMaxLength(lan.code),
              ...extraProps
            };
            return <div key={lan.code} className='input-language-modal-item'>
              <div className='input-language-modal-item-title'>
                {lan.comments}
              </div>
              <div className='input-language-modal-item-input'>
                {React.createElement(Comp, languageInputProps)}
              </div>
            </div>
          })}
        </Modal>
      </div>
    );
  }

  static PropTypes = {
    onChange: PropTypes.func,
    clickedI18n: PropTypes.func,
    clickedHideI18n: PropTypes.func,
    value: PropTypes.any,
    maxLength: PropTypes.array,
    placeholder: PropTypes.string,
    disabled: PropTypes.bool,
    textArea: PropTypes.bool,
    extraProps: PropTypes.object
  };

  static defaultProps = {
    placeholder: messages('common.please.input')/*请输入*/,
    extraProps: {}
  };

}

function mapStateToProps(state) {
  return {
    languageList: state.login.languageList,
    language: state.main.language
  }
}

const wrappedInputLanguage = connect(mapStateToProps)(InputLanguage);

//必填校验
wrappedInputLanguage.required = {
  validator: (rule, value, cb) => {
    if (!value || !value.name) {
      cb(messages('common.please.input')/*请输入*/);
    } else {
      cb();
    }
  }
};

export default wrappedInputLanguage;
